package com.qfedu.controller;

import com.qfedu.entity.ResponseData;
import com.qfedu.entity.User;
import com.qfedu.service.UserService;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findUserByNo")
    @ResponseBody
    public User findUserByNo(String no){

        return userService.findUserByNo(no);
    }

    /**
     * 是否登陆
     * @return
     */
    @RequestMapping("/isLogin")
    @ResponseBody
    public  ResponseData isLogin(HttpServletRequest httpServletRequest){

        HttpSession httpSession = httpServletRequest.getSession();
        Object user =   httpSession.getAttribute("loginUser");
        ResponseData responseData = new ResponseData();
        if (user!=null){

            responseData.setCode(ResponseData.SUCCESS_CODE);
            responseData.setMsg(ResponseData.SUCCESS_MSG);
            responseData.setData(user);
            return responseData;
        }

        responseData.setCode(ResponseData.FAIL_CODE);
        responseData.setMsg("重新登陆");
        return  responseData;
    }

    /**
     * 登陆
     * @param no
     * @param password
     * @return
     */
    @RequestMapping("/userlogin")
    @ResponseBody
    public ResponseData<User> login(String no, String password, HttpServletRequest request){

         User user =   userService.findUserByNo(no);

         ResponseData responseData = new ResponseData();
         if (user!=null){

             if ( user.getPassword().equals(password)){

                 responseData.setCode(ResponseData.SUCCESS_CODE);
                 responseData.setMsg(ResponseData.SUCCESS_MSG);
                 responseData.setData(user);
                 request.getSession().setAttribute("loginUser",user);

                 return responseData;
             }

             responseData.setCode(ResponseData.FAIL_CODE);
             responseData.setMsg("密码错误");
         }else {
             responseData.setCode(ResponseData.FAIL_CODE);
             responseData.setMsg("用户不存在");
         }


        return responseData;
    }

    @RequestMapping("/loginOut")
    @ResponseBody
    public ResponseData<User> loginOut(HttpServletRequest request){
        ResponseData responseData = new ResponseData();
        HttpSession session = request.getSession();
        session.invalidate();
        responseData.setCode(ResponseData.SUCCESS_CODE);
        responseData.setMsg("退出成功！");

        return responseData;

    }



}
